package org.west.sky.frame.activiti.study.util;

import org.activiti.engine.*;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;

import java.text.SimpleDateFormat;

/**
 * author: chz
 * date: 2024/9/12
 * description:
 */
public class ActivitiEngineUtil {

    protected static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    protected ProcessEngineConfiguration configuration;

    protected ProcessEngine processEngine;

    protected RepositoryService repositoryService;

    protected RuntimeService runtimeService;

    protected TaskService taskService;

    protected HistoryService historyService;

    protected ManagementService managementService;

    protected IdentityService identityService;

    protected void loadActivitiConfigAndInitEngine() {
        loadActivitiConfigAndInitEngine("activiti.cfg.xml");
    }

    protected void loadActivitiConfigAndInitEngine(String resourceName) {
        this.configuration = ProcessEngineConfiguration.createProcessEngineConfigurationFromResource(resourceName);
        this.processEngine = this.configuration.buildProcessEngine();
        this.repositoryService = this.processEngine.getRepositoryService();
        this.runtimeService = this.processEngine.getRuntimeService();
        this.taskService = this.processEngine.getTaskService();
        this.historyService = this.processEngine.getHistoryService();
        this.managementService = this.processEngine.getManagementService();
        this.identityService = this.processEngine.getIdentityService();
    }

    protected ProcessDefinition deployByClassPathResource(String resourceName) {
        Deployment deploy = this.repositoryService.createDeployment()
                .addClasspathResource(resourceName)
                .deploy();
        return repositoryService.createProcessDefinitionQuery().deploymentId(deploy.getId()).singleResult();
    }

    protected void closeEngine(){
        this.processEngine.close();
    }
}
